package main

import (
	"log"

	"fmt"

	"github.com/vinllen/mgo"
	"go.mongodb.org/mongo-driver/bson"
)

var mongoSession *mgo.Session // mongo连接对象
// mongo连接字符串
var mongoConnString string

func Connect(url string) error {
	if s, err := mgo.Dial(url); err == nil {
		log.Println(fmt.Sprintf("connect mongodb %s success", url))
		s.SetMode(mgo.Monotonic, true)
		mongoSession = s
	} else {
		log.Println(fmt.Sprintf("connect mongodb %s failed: %s", url, err.Error()))
		return err
	}
	return nil
}

func GetCollection(collection string) *mgo.Collection {
	if nil == SessionPool() {
		log.Println("can not find mongo session: %s", mongoConnString)
	}

	return SessionPool().DB("").C(collection)
}

/**
 * @brief: 设置配置
 */
func SetConfig(connString string) {
	mongoConnString = connString
	Connect(mongoConnString)
}

/**
 * @brief: 从会话池获取会话
 */
func SessionPool() *mgo.Session {
	if nil == mongoSession {
		Connect(mongoConnString)
	}

	return mongoSession
}

type User struct {
	Name     string `bson:"name" json:"name"`
	Password string `bson:"password" json:"password"`
}

func main() {
	var url1 = "mongodb://root:MTAE379673#@10.96.8.100:27017/testtest?readPreference=secondaryPreferred&authSource=admin"
	SetConfig(url1)

	db := GetCollection("users")

	//添加一条数据
	err := db.Insert(bson.M{"name": "jack", "password": "123"})
	if err != nil {
		fmt.Println("添加失败,err=" + err.Error())
		return
	}

	user := &User{}
	//查询数据
	err = db.Find(bson.M{"name": "jack", "password": "123"}).One(user)
	if err != nil {
		fmt.Println("查询失败,err=" + err.Error())
		return
	}

	//更新数据
	err = db.Update(bson.M{"name": "jack"}, bson.M{"$set": bson.M{"password": "654321"}})
	if err != nil {
		fmt.Println("更新失败,err=" + err.Error())
		return
	}

	//删除数据
	err = db.Remove(bson.M{"name": "jack"})
	if err != nil {
		fmt.Println("删除失败,err=" + err.Error())
		return
	}
}
